// pages/food/food.js
let db = wx.cloud.database();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchKey: "",
        foodList: [],
        totalPrice: 0,
        totalNum: 0,
        cartList: [],
        isShowMask: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let searchKey = options.searchKey;

          //获取购物车数据
          let cartList = wx.getStorageSync('cart') || [];
          this.setData({
              cartList
          })

        if (searchKey) {
            //搜索菜品
            this.getFoodList('search', searchKey)
            wx.setNavigationBarTitle({
                title: '搜索页',
            })
            this.setData({
                searchKey: searchKey //搜索词
            })
        } else {
            //获取菜品数据
            wx.setNavigationBarTitle({
                title: '菜单页',
            })
            this.getFoodList('getAll')
        }

      
    },
    //获取用户输入的搜索词
    getSearchKey(e) {
        this.setData({
            searchKey: e.detail.value //搜索词
        })
    },
    //搜索事件
    goSearch() {
        this.getFoodList('search', this.data.searchKey)
    },
    //获取菜品数据
    getFoodList(action, searchKey) {

        wx.cloud.callFunction({
            name: "getFoodList",
            data: {
                action: action,
                searchKey: searchKey
            }
        }).then(res => {
            //遍历
            let dataList = res.result.data;
            let cartList= this.data.cartList;
            let totalNum = this.data.totalNum;
            let totalPrice= this.data.totalPrice;

            dataList.forEach(food => {
           
                if(cartList && cartList.length>0){
                  
                    let result = cartList.find(cart=>{
                        return cart._id==food._id;
                    })
       //如果购物车存在这个商品
                    if(result){
                        food.quantity = result.quantity;
                        totalNum+=food.quantity;
                        totalPrice+=food.quantity*food.price;
                    }else{
                       food.quantity = 0;
                    }
                }else{
                    food.quantity = 0;
                }

                console.log("food",food)

            });
            this.setData({
                foodList: dataList,
                totalPrice,
                totalNum
            })

           
        }).catch(err => {
            console.log("菜品数据请求失败", err);
        }
        )
    },

    // 减少菜品
    minusCount(event) {
        let id = event.currentTarget.dataset.item;
        let foodList = this.data.foodList;
        let cartList = wx.getStorageSync('cart') || [];
        foodList.forEach(food => {
            if (food._id == id) {
                if (food.quantity > 0) {
                    food.quantity -= 1;
                    //从购物车减去
        
                    let index = cartList.findIndex(cart => {
                        return cart._id == id;
                    })

                    let res = cartList.find(cart => {
                        return cart._id == id;
                    })

                   if(res){
                       res.quantity = food.quantity;
                   }
                   if(food.quantity==0){
                       cartList.splice(index,1);
                   }

                    wx.setStorageSync('cart', cartList);
                    this.setData({
                        totalNum: this.data.totalNum - 1,
                   totalPrice: this.data.totalPrice - food.price,
                        cartList

                    })
                } else {
                    wx.showToast({
                        icon: "none",
                        title: '商品个数必须大于0',
                    })
                }
            }
        })

        this.setData({
            foodList
        })

    },
    addCount(event) {
        let id = event.currentTarget.dataset.item;

        let foodList = this.data.foodList;
        foodList.forEach(food => {
            if (food._id == id) {
                food.quantity += 1;
                let cartList = wx.getStorageSync('cart') || [];
                //加入购物车
                if (cartList && cartList.length > 0) {
                    let res = cartList.find(item => {
                        return item._id == id;
                    })

                    //购物车不存在该商品
                    if (!res) {
                        cartList.push(food);

                    } else {
                        res.quantity = food.quantity;
                    }
                } else {
                    cartList.push(food);
                }

                //加入缓存
                wx.setStorageSync('cart', cartList);
                this.setData({
                    totalNum: this.data.totalNum + 1,
                    totalPrice: this.data.totalPrice + food.price,
                    cartList
                })
            }
        })

        this.setData({
            foodList
        })


    },
    // 打开购物车
    openMask() {
        this.setData(
            {
       isShowMask:true
            }
        )
    },

       // 关闭购物车
       closeMask() {
        this.setData(
            {
       isShowMask:false
            }
        )
    },
    clearCart(){
      
   wx.removeStorage({
     key: 'cart',
   })

   let foodList = this.data.foodList;
   foodList.forEach(food=>{
       food.quantity = 0;
   })
        this.setData({
            totalNum:0,
            totalPrice:0,
            cartList:[],
            foodList
        })

    },
    //删除购物车某个项
    deleteCartItem(e){
        let index = e.currentTarget.dataset.item;
        let foodList = this.data.foodList;
        let totalNum = this.data.totalNum;
        let totalPrice = this.data.totalPrice;
        let cartList = this.data.cartList;
        let cart = cartList[index];
        
    
        totalNum-=cart.quantity;
        totalPrice-=cart.quantity*cart.price;
 
        foodList.forEach(food=>{
            if(food._id == cart._id){
                food.quantity= 0;
            }
        })
        cartList.splice(index,1);
           
        this.setData({
            cartList,
            foodList,
            totalNum,
            totalPrice
        })
        wx.setStorageSync('cart', cartList)   
    },
 
    gotoOrder(){
        wx.navigateTo({
          url: '/pages/pay/pay',
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})